import { Compiler, Component, ComponentRef, Injector, ViewChild, ViewContainerRef, EventEmitter, Output } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { EntityDtoOfGuid, PaperIdInput, PaperState, RollBackInput, SuperFormDataOutput, UpdateAdditionalMsgInput, UpdateFormDataInput, UpdateReplyInput, WorkFlowManagerServiceProxy } from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { DateTime } from 'luxon';
import { WorkFlowHelper } from '@app/shared/common/workflow/workflow-helper.service';
import { IBackWorkFlowListData, IFlowDetailParam, IRemarkDataItem, ITranslateItem } from '@app/shared/common/workflow/workflow-common-interface';
import { HtmlHelper } from '@shared/helpers/HtmlHelper';
import { AppModalComponentBase } from '@shared/common/app-modal-component-base';
import { AppBsModalService } from '@shared/common/appBsModal/app-bs-modal.service';
import { createWfFormComponentFactory } from '@app/main/workflow/workflow-detal-form-factory';
import { ReplyMsgUpdateModelComponent } from './reply-message-update-modal.component';
import { AuditTimeEditModelComponent } from './audit-time-edit-modal.component';

@Component({
    selector:'workFlowManagerDetail',
    templateUrl: './workflow-manager-detail.component.html',
    animations: [appModuleAnimation()],
    styleUrls: ['../../main/workflow/workflow-detail.component.css'],
})
export class WorkflowManagerDetailComponent extends AppModalComponentBase {
    @ViewChild('detailModal', { static: true}) modal: ModalDirective;
    @ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef;

    @Output() backListEvent: EventEmitter<IBackWorkFlowListData> = new EventEmitter<IBackWorkFlowListData>();
    private cmpRef: ComponentRef<any>;
    
    paperId:string;
    adminPermission: boolean = false;

    replyMsg:string;
    remarkData: IRemarkDataItem[] = [];
    passRoundData: ITranslateItem[] = [];

    fieldDisabledData:{[key:string]:boolean};
    formData:{ [key: string]: any; };
    workFlowData: SuperFormDataOutput = new SuperFormDataOutput();

    canEditAttach:boolean = false;
    paperState:PaperState;
    isTitleEdit:boolean = false;

    saving:boolean = false;

    //btnEnabled = false;
    
    isLoading = false;

    hadChangedData = false;

    isLoadingModal = false;

    wfUniqueName: {[key:string]:string} = {
        //bj: '收文办件'
    };

    constructor(
        public injector: Injector,
        private _workFlowManagerService: WorkFlowManagerServiceProxy,
        private _workFlowHelper:WorkFlowHelper,
        private compiler: Compiler,
        private _modalService: AppBsModalService
    ) {
        super(injector);
        this.adminPermission = this.isGranted('Pages.Manage.WorkFlow.Admin');
    }


    show(moduleParams: IFlowDetailParam): void {
        this.ngOnDestroy();
        this.modalExpandOb.resetStates();
        this.hadChangedData = false;
        this.resertInitData();
        this.paperId = moduleParams.paperId;
        this.getWorkFlowData();
    }


    getWorkFlowData(){
        if (this.isLoadingModal) return;
        this.isLoadingModal = true;
        this.modal.show();

        this.isLoading = true;
        this._workFlowManagerService.getFormDataForEdit(this.paperId).pipe(finalize(()=>{
            this.isLoading = false;
            this.isLoadingModal = false;
        })).subscribe(result=>{
            this.workFlowData = result;
            this.paperState = result.paper.paperState;
            this.canEditAttach = result.canEditAttachment;
            
            this.formData = result.formData.data;
            this.fieldDisabledData = result.formData.fieldDisabled;

            this.workFlowData.formHtml = HtmlHelper.htmlDecode(result.formHtml);
            this.remarkData = this._workFlowHelper.getRemarkData(this.workFlowData.remarkData,this.workFlowData.additionalMsg)
            this.passRoundData = this._workFlowHelper.getPassRoundData(this.workFlowData.remarkData);
            
            this.createComponent(this.vc);
        })
    }

    workflowSave(){
        this.isLoading = true;
        this.beforeSave();
        var fromValues = this.formData;
        var paper = Object.assign({}, this.workFlowData.paper);
        this._workFlowManagerService.updateFormData(
            new UpdateFormDataInput({ id: this.paperId, paper: paper , values: fromValues }))
            .pipe(finalize(()=>{this.isLoading = false;}))
            .subscribe(result=>{
                this.notify.success(this.l('SavedSuccessfully'));
                this.hadChangedData = true;
                this.close();
        });
    }

    close(): void {
        this.modal.hide();
        if (this.hadChangedData){
            this.backListEvent.emit({isReload:true});
        }
    }
  
    ngOnDestroy() {
        if(this.cmpRef) {
          this.cmpRef.destroy();
        }
    }

    downAttach(filePath:string){
        if (!filePath) return;
        window.open(filePath);
    }

      /**
     * 保存前
     */
    beforeSave(){

    }

    checkState(data: ITranslateItem){
        return this._workFlowHelper.checkState(data);
    }

    timeDiffCalc(state:number, markTime:DateTime, finishedTime:DateTime){
        return this._workFlowHelper.timeDiffCalc(state, markTime, finishedTime);
    }

    timeFormat(time:DateTime){
        return this._workFlowHelper.timeFormat(time);
    }

    goBackList(){
        this.modal.hide();
        this.backListEvent.emit({isReload:true});
    }
    
    protected createComponent(ref: ViewContainerRef) {
        let that = this;
        let tempFunc = function () {
            this.formData = that.formData;
            this.fieldDisabledData = that.fieldDisabledData;
            this.paperId = that.paperId;
        };
        createWfFormComponentFactory(this.compiler, this.workFlowData.formHtml, tempFunc).then(factory => {
          const injector = Injector.create({ providers: [], parent: ref.injector });
          const cmpRef = ref.createComponent(factory, 0, injector, []);

          cmpRef.instance.name = "dynamic-wf-component";
          this.cmpRef = cmpRef;
        });
      }

    private resertInitData():void{
        this.workFlowData = new SuperFormDataOutput();
        this.fieldDisabledData = {};
        this.formData = {};
        this.replyMsg = "";
        this.remarkData = [];
        this.passRoundData = [];
    }


    archive() {
        this.message.confirm('是否确认归档', this.l('AreYouSure'),
            (isConfirmed) => {
                if (!isConfirmed) return;
                this.isLoading = true;
                this._workFlowManagerService.archive(new PaperIdInput({
                    paperId: this.paperId
                }))
                    .pipe(finalize(() => this.isLoading = false))
                    .subscribe(() => {
                        this.notify.success(this.l('ExecuteSuccessfully'));
                        this.hadChangedData = true;
                        this.close();
                    });
            })
    }

    //回退
    rollBack (taskId) {
        this.message.confirm('是否确认回退', this.l('AreYouSure'),
        (isConfirmed) => {
            if (!isConfirmed) return;
            this.isLoading = true;
            this._workFlowManagerService.rollBack(new RollBackInput({
                taskId :taskId,
                paperId: this.paperId
            }))
                .pipe(finalize(() => this.isLoading = false))
                .subscribe(() => {
                    this.notify.success(this.l('ExecuteSuccessfully'));
                    this.hadChangedData = true;
                    this.close();
                });
        })
    };
    updateReplyMsg (item) {
        const bsModalRef = this._modalService.show(ReplyMsgUpdateModelComponent, {
            backdrop: 'static', class: 'modal-lg'
        });

        bsModalRef.content.shown(item.reply);
        bsModalRef.content.callback = (result: string) => {
            this._workFlowManagerService.updateReplyMsg(new UpdateReplyInput({
                taskId: item.id,
                replyMsg: result
            })).subscribe(result2=>{
                bsModalRef.hide();
                item.reply = result;
                this.notify.success(this.l('SavedSuccessfully'));
            })
        };
    };
    updateAdditionalMsg(item) {
        const bsModalRef = this._modalService.show(ReplyMsgUpdateModelComponent, {
            backdrop: 'static', class: 'modal-lg'
        });
        bsModalRef.content.shown(item.reply);
        bsModalRef.content.callback = (result: string) => {
            this._workFlowManagerService.updateAdditionalMsg(new UpdateAdditionalMsgInput({
                msgId: item.taskId,
                replyMsg: result
            })).subscribe(result2=>{
                bsModalRef.hide();
                item.reply = result;
                this.notify.success(this.l('SavedSuccessfully'));
            })
        };
    };

    //作废
    invalid() {
        this.message.confirm('是否确认作废', this.l('AreYouSure'),
        (isConfirmed) => {
            if (!isConfirmed) return;
            this.isLoading = true;
            this._workFlowManagerService.cancel([this.paperId])
                .pipe(finalize(() => this.isLoading = false))
                .subscribe(() => {
                    this.notify.success(this.l('ExecuteSuccessfully'));
                    this.hadChangedData = true;
                    this.close();
                });
        })
    };
    //从作废状态恢复到执行中
    restore () {
        this.isLoading = true;
        this._workFlowManagerService.restore([this.paperId])
            .pipe(finalize(() => this.isLoading = false))
            .subscribe(() => {
                this.notify.success(this.l('ExecuteSuccessfully'));
                this.hadChangedData = true;
                this.close();
            });
    };
    //删除作废稿件
    superDelete () {
        this.message.confirm('是否确认删除作废稿件，删除后无法恢复', this.l('AreYouSure'),
        (isConfirmed) => {
            if (!isConfirmed) return;
            this.isLoading = true;
            this._workFlowManagerService.superDelete([this.paperId])
                .pipe(finalize(() => this.isLoading = false))
                .subscribe(() => {
                    this.notify.success(this.l('SuccessfullyDeleted'));
                    this.hadChangedData = true;
                    this.close();
                });
        })
    };
    //已办结的稿件，恢复为继续办理
    resumeExecute() {
        this.isLoading = true;
        this._workFlowManagerService.resumeExecute(new PaperIdInput({
            paperId: this.paperId
        }))
            .pipe(finalize(() => this.isLoading = false))
            .subscribe(() => {
                this.notify.success(this.l('ExecuteSuccessfully'));
                this.hadChangedData = true;
                this.close();
            });
    };
    // vm.print = function () {
    //     var pageName = 'Print';
    //     if (vm.workFlowData.wfUniqueName === vm.wfUniqueName.bj) {
    //         pageName = 'BjPrint';
    //     } else if (vm.workFlowData.wfUniqueName === vm.wfUniqueName.yj) {
    //         pageName = 'YjPrint';
    //     }
    //     window.open("/WorkFlow/" + pageName + "?paperId=" + vm.paperId + "&archived=0&tt=" + new Date().getTime(), 'print' + vm.paperId, 'menubar=0,toolbar=0,status=1,scrollbars=1,resizable=1');
    //     //window.open("/WorkFlow/Print?paperId=" + vm.paperId + "&archived=0&tt=" + new Date().getTime(), 'print' + vm.paperId, 'menubar=0,toolbar=0,status=1,scrollbars=1,resizable=1');
    // };

    setUnMarked (item) {
        this.isLoading = true;
        this._workFlowManagerService.setPaperUnMarked(new EntityDtoOfGuid({
            id: item.id
        }))
            .pipe(finalize(() => this.isLoading = false))
            .subscribe(() => {
                this.notify.success(this.l('ExecuteSuccessfully'));
                item.markedTime = null;
            });
    }

    updateAuditTime (item) {
        const bsModalRef = this._modalService.show(AuditTimeEditModelComponent, {
            backdrop: 'static', class: 'modal-lg'
        });

        bsModalRef.content.shown(item);
        bsModalRef.content.callback = (result) => {
            if (result) {
                item.startTime = result.startTime;
                item.markedTime = result.markedTime;
                item.finishedTime = result.finishedTime;
            }
        };
    };
}





